﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using HtmlAgilityPack;

namespace Lou.Client.Authentication
{
    public class AuthenticationManager
    {
        private readonly string _login;
        private readonly string _password;
        private readonly Dictionary<string, Connection> _tokens = new Dictionary<string, Connection>();
        public Dictionary<string, Connection> Worlds { get { return this._tokens; } }

        public AuthenticationManager(string login, string password)
        {
            this._login = login;
            this._password = password;
            this.GetTokens();
        }

        private void GetTokens()
        {
            CookieContainer jar = new CookieContainer();
            jar.Add(new Cookie("is_returning", "1", "/", "www.lordofultima.com"));
            string page = Post(@"https://www.lordofultima.com/en/user/login", jar, new Dictionary<string, string>
            {
                { "mail", this._login },
                { "password", this._password },
            });
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(page);

            _tokens.Clear();
            doc.DocumentNode.SelectNodes("//form").Where(a => a.Attributes["action"].Value.Contains("prodgame")).Select(n =>
                new Connection
                {
                    Url = n.Attributes["action"].Value,
                    SessionId = new Guid(n.NextSibling.NextSibling.Attributes["value"].Value),
                    Label = n.NextSibling.NextSibling.NextSibling.NextSibling.FirstChild.NextSibling.Attributes["value"].Value,
                }).ToList().ForEach(a => _tokens.Add(a.Label, a));
        }

        private string Get(string url, CookieContainer jar)
        {
            return Request(url, "GET", jar);
        }

        private string Post(string url, CookieContainer jar, Dictionary<string, string> postData)
        {
            return Request(url, "POST", jar, postData);
        }

        private string Request(string url, string method, CookieContainer jar, Dictionary<string, string> data = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = method;
            request.CookieContainer = jar;
            if (data != null)
            {
                request.ContentType = "application/x-www-form-urlencoded";
                byte[] postData = Encoding.UTF8.GetBytes(string.Join("&", data.Select(a => HttpUtility.UrlEncode(a.Key) + "=" + HttpUtility.UrlEncode(a.Value))));
                request.ContentLength = postData.Length;
                request.GetRequestStream().Write(postData, 0, postData.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
    }
}
